package com.new4net.reactor;

import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
public class Demultiplexer {

    public List<Command> select(Subject subject, Map<Object, List<EventHandler>> eventHandlers) {
        synchronized (eventHandlers){
            Set<Object> events = eventHandlers.keySet();
            if(events==null||events.size()==0){
                return new ArrayList<>();
            }
            EventHolder eventHolder = subject.fire(events);
            if(eventHolder==null){
                return new ArrayList<>();
            }
            return Optional.of(eventHandlers.get(eventHolder.getEvent()))
                    .orElse(new ArrayList<>())
                    .stream()
                    .map(eventHandler -> {
                        Command command = new Command() {
                            @Override
                            public void executeCommand() {
                                try {
                                    eventHandler.handle(eventHolder);
                                } catch (Exception e) {
                                    log.error("some error happened in eventHandler "+subject.getName()+" when fire the event,", e);

                                }
                            }
                        };
                        command.setSubjectName(subject.getName());
                        return command;
                    })
                    .collect(Collectors.toList());
        }

    }


}
